<template>
    <div class="warpper-box">
        <form-create 
        v-model="params.fApi" 
        :rule="params.rule" 
        :option="params.option" 
        @btn-search-click="loadTable(true)"
        @btn-reset-click="reset"/>
        <a-button type="danger" icon="plus" v-action:contractTempAddBtn @click="add(true)">新增</a-button>
        <a-table :columns="table.columns" :pagination="table.pagination" @change="handleTableChange" rowKey="id" :data-source="table.loadData">
          <span slot="status" slot-scope="text, record">
            <span v-if="userInfo.type === 1">
              <a-popconfirm
                :title="record.status === 1 ? '禁用状态，模板不能使用？确认禁用！':'确认启用！'"
                ok-text="确认"
                cancel-text="取消"
                @confirm="handelTempStatusChange(record)" >
                 <a-switch checked-children="启用" un-checked-children="禁用" 
                :checked="record.status === 1 ? true : false"
                default-checked />
              </a-popconfirm>
            </span>
            <span v-else>
              {{record.status === 1?'已启用':'已禁用'}}
            </span>
          </span>
          <span slot="fileUrl" slot-scope="text, record">
            <a @click="previewFileChage(record)">预览</a>
          </span>
          <span slot="action" slot-scope="text, record">
            <a @click="add(record)" v-action:contractTempEditBtn>编辑</a>
          </span>
        </a-table>
         <a-modal title="新增" :width="640" :visible="form.visible" :confirmLoading="submitLoading" @ok="handleSubmit" @cancel="form.visible=false">
            <form-create v-model="form.fApi" :rule="form.rule"  @btn-file-click="fileUpload" :option="form.option"/>
            <input type="file" ref="fileRef" accept="application/pdf" @change="fileChange" style="display: none;" />
        </a-modal>
    </div>
</template>

<script>
import { mapGetters } from 'vuex'
import store from '@/store'
import { 
    getSysContractTempList,
    getSysContractTempAdd,
    getSysContractTempEdit,
    getSysContractTempEnable
} from '@/api/manage/contractTemp'
import { sysBaseUpload } from '@/api/manage/base'
import { previewFile } from '@/utils/util'
import {
    PARAMS_CONTRACT_TEMP,
    FORM_CONTRACT_TEMP,
    COLUMNS_CONTRACT_TEMP,
    OPTION_BLOCK,
    OPTION_INLINE
} from '../modules/form'
export default {
  name: 'contractTempList',
  data () {
    return {
        params:{
          fApi:{},
          rule:PARAMS_CONTRACT_TEMP,
          option:OPTION_INLINE
        },
        form:{
          id:'',
           visible:false,
          fApi:{},
          rule:[],
          option:OPTION_BLOCK
        },
        table:{
          columns:COLUMNS_CONTRACT_TEMP,
          loadData:[],
          pagination:{
            current:1,
            pageSize: 10,
            total:0,
            showSizeChanger: true,
					showQuickJumper: true,
            pageSizeOptions: ["10", "20", "50", "100"],
            showTotal: total => `共有 ${total} 条数据`,
          }
        },
        fileUrl:'',
        submitLoading:false
    }
  },
  computed: {
    ...mapGetters(['userInfo'])
  },
  watch: {
    "userInfo":{
      handler(newData, oldData) {
        this.$nextTick(()=>{
          if(newData.type === 1){
              this.params.fApi.hidden(false,'add');
          }else{
              this.params.fApi.hidden(true,'add');
          }
        })
      },
      deep: true,
      immediate: true
    }
  },
  created () {
    this.loadTable(true);
  },
  methods: {
    async loadTable(flag){
      let params = {};
      if(JSON.stringify(this.params.fApi) !== "{}"){
        params.name = this.params.fApi.getValue('name');
      }
      if(flag){
        this.table.pagination.current = 1;
        this.table.pagination.pageSize = 10;
      }
      params.pageNum = this.table.pagination.current;
      params.pageSize = this.table.pagination.pageSize;
      const {code,data} = await getSysContractTempList(params);
      if(code ==='1'){
        this.table.loadData = data.content;
        this.table.pagination.total = data.total || 0;
      }
    },
    handleTableChange(pagination){
      this.table.pagination.current = pagination.current;
      this.table.pagination.pageSize = pagination.pageSize;
      this.loadTable(false);
    },
    async add(rows){
        this.form.rule = FORM_CONTRACT_TEMP;
        const parks = await store.dispatch('getSysAllParkEnable');
        if(rows == true){
          this.form.id = '';
          this.fileUrl ='';
          this.title="新增";
          this.form.visible = true;
          this.$nextTick(()=>{
            this.form.fApi.updateRules({'parkIds':{options:parks,title:'关联园区（支持多选）',props:{mode:'multiple'}}});
            this.form.fApi.resetFields();
          });
        }else{
          this.form.id = rows.id;
          this.fileUrl =rows.fileUrl;
          this.title="编辑";
          this.form.visible = true;
          this.$nextTick(()=>{
            this.form.fApi.updateRules({'parkIds':{options:parks,title:'关联园区',props:{mode:''}}});
            const model = this.form.fApi.model();
            for(var keys in rows){
              model[keys] = rows[keys];
            }
            model.parkIds = rows.parkId;
            this.form.fApi.coverValue(model)
          });
        }
        
    },
    fileUpload(){
        this.$refs.fileRef.click();
    },
    async fileChange(e){
        e.preventDefault();
        let _this = this;
        let file = e.target.files[0];
        if(file===undefined){return;}
        if (file.name.indexOf('.pdf') === -1) {
            _this.$message.error("只支持pdf文件格式");
            e.target.value= "";
            return;
        }
        const isSize = file.size / 1024 / 1024 < 20
        if (!isSize) {
            _this.$message.error('文件不得大于20MB!');
            e.target.value= "";
            return;
        }
        let formData = new FormData();
        formData.append("file",file);
        const {code,data} = await sysBaseUpload(formData);
        if(code === '1'){
            this.fileUrl = data;//临时储存
            this.form.fApi.setValue({"fileUrl":file.name});
            e.target.value = "";
        }
    },
    handleSubmit(){
      this.form.fApi.submit(async (formData, $f) => {
        try {
          if(!this.fileUrl){
            return this.$message.error('请上传文件');
          }
          if(this.form.id){
            formData.id = this.form.id;
          }else{
            formData.parkIds = formData.parkIds.join(',');
          }
          formData.fileUrl = this.fileUrl;
          this.submitLoading = true;
          const {code} = this.form.id ? await getSysContractTempEdit(formData) : await getSysContractTempAdd(formData);
          this.submitLoading = false;
          if(code === '1'){
            this.form.visible = false;
            this.loadTable(true);
          }
        } catch (error) {
          this.$message.info(JSON.stringify(error));
        }
      })
    },
    async handelTempStatusChange(el){
      const status = el.status === 1 ? 2:1;
      let params = {
        status:status,
        id:el.id
      }
      const {code} = await getSysContractTempEnable(params);
      if(code === '1'){
        this.$message.success('操作成功');
        this.loadTable(false);
      }
    },
    previewFileChage(rows){
        previewFile(rows.fileUrl);
    },
    reset(){
      this.params.fApi.resetFields();
      this.loadTable(true);
    }
  }
}
</script>


